package com.hanqi.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hanqi.entity.SysRole;
import com.hanqi.service.SysRoleService;
import com.hanqi.util.PinyinUtil;
import com.hanqi.util.R;
import com.hanqi.util.UUIDGenerator;
import com.hanqi.util.shiro.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zjk
 * @since 2019-04-27
 */
@Controller
@RequestMapping("/sysRole")
public class SysRoleController {

    @Autowired
    protected SysRoleService sysRoleService;

    @RequestMapping("/index")
    public String index() {
        return "page/roleList";
    }

    @ResponseBody
    @RequestMapping("/list")
    public List<SysRole> list() {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag", 0);
        return sysRoleService.list(queryWrapper);
    }

    @ResponseBody
    @RequestMapping("/insert")
    public JSONObject insert(SysRole sysRole) {
        sysRole.setId(UUIDGenerator.getUUID());
        sysRole.setCreateDate(LocalDateTime.now());
        sysRole.setCreateName(ShiroUtil.getUserEntity().getRname());
        sysRole.setDeleteFlag(0);
        String roleName = sysRole.getRolename();
        sysRole.setPermissions(PinyinUtil.getPingYin(roleName));
        boolean r = sysRoleService.save(sysRole);
        if (r) {
            return R.SUCCESS;
        }
        return R.FAIL;
    }

    @ResponseBody
    @RequestMapping("/update")
    public JSONObject update(SysRole sysRole) {
        boolean r = sysRoleService.updateById(sysRole);
        if (r) {
            return R.SUCCESS;
        }
        return R.FAIL;
    }

    @ResponseBody
    @RequestMapping("/delete")
    public JSONObject delete(String ids) {
        String[] idCollect = ids.split(",");
        boolean r = sysRoleService.removeByIds(Arrays.asList(idCollect));
        if (r) {
            return R.SUCCESS;
        }
        return R.FAIL;
    }

    @ResponseBody
    @RequestMapping("/roleListByUserId")
    public JSONObject roleListByUserId(String userId) {
        List<Map<String, Object>> list = sysRoleService.roleListByUserId(userId);
        return R.msg(true, "", list);
    }
}
